﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Auditing;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using DHJ.Cost.RealTimeCost.Dto;
using Microsoft.EntityFrameworkCore;

namespace DHJ.Cost.RealTimeCost
{
    public class EstimatedCostMessageAppService : CostAppServiceBase, IEstimatedCostMessageAppService
    {
        private readonly IRepository<EstimatedCost, Guid> _estimatedCostRepository;
        private readonly IRepository<EstimatedCostMessage, Guid> _estimatedCostMessageRepository;

        public EstimatedCostMessageAppService(
            IRepository<EstimatedCost, Guid> estimatedCostRepository, IRepository<EstimatedCostMessage, Guid> estimatedCostMessageRepository)
        {
            _estimatedCostRepository = estimatedCostRepository;
            _estimatedCostMessageRepository = estimatedCostMessageRepository;
        }
        [DisableAuditing]
        public async Task<int> GetUnreadCostMessagesCount()
        {
            var userId = AbpSession.GetUserId();

            return await _estimatedCostMessageRepository.GetAll().Where(e => e.UserId == userId && !e.Read)
                .CountAsync();
        }
        [DisableAuditing]
        public async Task<ListResultDto<EstimatedCostMessageDto>> GetCostMessages(GetUserCostMessagesInput input)
        {
            var userId = AbpSession.GetUserId();

            EstimatedCostMessage minMessage = null;

            if (input.MinMessageId.HasValue)
            {
                minMessage = await _estimatedCostMessageRepository.GetAsync(input.MinMessageId.Value);

            }

            var messages = await _estimatedCostMessageRepository.GetAll().Include(e => e.Cost)
                .WhereIf(minMessage != null, m => m.CreationTime < minMessage.CreationTime)
                .Where(e => e.UserId == userId)
                .OrderByDescending(m => m.CreationTime)
                .Take(50)
                .ToListAsync();

            messages.Reverse();

            return new ListResultDto<EstimatedCostMessageDto>(ObjectMapper.Map<List<EstimatedCostMessageDto>>(messages));
        }

        public async Task MarkAllUnreadMessagesOfUserAsRead()
        {
            var userId = AbpSession.GetUserId();

            var costs = await _estimatedCostMessageRepository.GetAll()
                .Where(e => e.UserId == userId && !e.Read)
                .ToListAsync();

            foreach (var cost in costs)
            {
                cost.Read = true;
            }
        }
    }
}